<template>
  <f7-page>
    <qm-currentcy-navbar title="应用管理"></qm-currentcy-navbar>
    <transition name="lyric">
      <div class="preservation" v-if="editing">
        <f7-row>
          <f7-col width="20">
            <f7-button outline small @click="onCancel()">取消</f7-button>
          </f7-col>
          <f7-col width="20">
            <f7-button fill small @click="onSave()">保存</f7-button>
          </f7-col>
        </f7-row>
      </div>
    </transition>
    <div class="out">
      <qm-block title="我的应用" :smtitle="editing?'（长按拖动排序）':''">
        <div>
          <draggable
            element="ul"
            v-model="commonly"
            class="qm-entry"
            :disabled="disabled"
            delay="500"
          >
            <qm-entry-miniapp
              v-for="(item, index) in commonly"
              :key="index"
              :data="item"
              :parmas="parmas"
              :reduce="reduceEditing"
              :editing="editing"
              iconWidth="64"
              fontSize="24"
              @delete="onDelete(item.serverId)"
            ></qm-entry-miniapp>
          </draggable>
        </div>
        <div class="title-footer" v-if="titleFooter">该区域最多可添加15个应用，超出的部分请先移除后再添加</div>
        <template v-slot:after-title v-if="!editing">
          <f7-button fill small @click="onEdit()" style="margin-right:20px">编辑</f7-button>
        </template>
      </qm-block>
      <qm-block :title="items.serverName" v-for="(items, index) in application" :key="index">
        <div class="qm-entry">
          <qm-entry-miniapp
            v-for="(item, index) in items.children"
            :key="index"
            :data="item"
            :parmas="parmas"
            :plus="plusEditing"
            :myapp="commonly"
            :editing="editing"
            iconWidth="64"
            fontSize="24"
            @increase="onAdd"
          ></qm-entry-miniapp>
        </div>
      </qm-block>
    </div>
  </f7-page>
</template>

<script>
import draggable from "vuedraggable";
export default {
  components: {
    //调用组件
    draggable,
  },
  data() {
    return {
      // 显示添加过多文字
      titleFooter: false,
      // 显示加号
      plusEditing: false,
      // 显示减号
      reduceEditing: false,
      // 所有应用
      entry: [],
      // 常用应用
      commonly: [],
      // 是否处于编辑状态
      editing: false,
      // 是否禁止拖拽
      disabled: true,
      // 小程序解析参数
      parmas: JSON.parse(localStorage.getItem("miniapp_parmas") || "{}"),
    };
  },
  computed: {
    // 应用类型排序
    application() {
      return this.sortByKey(this.entry, "sort");
    },
  },
  methods: {
    // 对数据进行排序
    sortByKey(array, key) {
      array.forEach((item) => {
        if (item.children) {
          this.sortByKey(item.children, "sort");
        }
      });
      return array.sort(function (a, b) {
        var x = a[key];
        var y = b[key];
        return x < y ? -1 : x > y ? 1 : 0;
      });
    },
    // 增加事件
    onAdd(data) {
      this.commonly.push(data);
      if (this.commonly.length >= 15) {
        this.plusEditing = false;
        this.titleFooter = true;
        return;
      }
    },
    // 删减事件
    onDelete(serverId) {
      if (this.commonly.length < 2) {
        this.reduceEditing === false;
        this.$f7.dialog.confirm("至少需要保留一个应用");
        return;
      }
      this.titleFooter = false;
      this.plusEditing = true;
      this.commonly.splice(
        this.commonly.findIndex((r) => r.serverId === serverId),
        1
      );
    },
    // 编辑
    onEdit() {
      this.reduceEditing = true;
      this.editing = true;
      this.disabled = false;
      if (this.commonly.length >= 15) {
        this.plusEditing = false;
        this.titleFooter = true;
        return;
      }
      this.plusEditing = true;
    },
    // 取消
    onCancel() {
      this.getFrequently();
      this.reduceEditing = false;
      this.plusEditing = false;
      this.editing = false;
      this.disabled = true;
      this.titleFooter = false;
    },
    // 保存
    onSave() {
      this.reduceEditing = false;
      this.plusEditing = false;
      this.editing = false;
      this.disabled = true;
      this.titleFooter = false;
      let postModel = {
        windowsId : window.plus.webview.currentWebview().id,
        columns : []
      };
      this.commonly.forEach((r,i) =>
        postModel.columns.push({ functionId: r.serverId, sort: i+1 })
      );

      this.$f7.preloader.show();
      window.qmsdk.callEvent("setFrequently",{
        ...postModel,
        ...{
          success: (r)=>{
            this.$f7.preloader.hide();
            if (r && r.success) {
              this.$f7.dialog.alert("保存成功");
            } else {
              this.$f7.dialog.alert(r.message || "保存失败");
            }
          },
          fail: (e)=>{
            this.$f7.preloader.hide();
            this.$f7.dialog.alert("保存失败");
          }
        }
      });
    },
    getFunctionOptions() {
      this.$f7.preloader.show();
      window.qmsdk.callEvent("getFunctionOptions",{
        userId: this.$f7.data.currentUser.userId,
        appCode: this.$f7.id || window.plus.runtime.appid,
        windowsId: window.plus.webview.currentWebview().id,
        success: (r)=>{
          this.$f7.preloader.hide();
          if (r && r.success) {
            this.entry = r.data;
          } else {
            this.$f7.dialog.alert("无法获取数据，请重新登录后尝试");
          }
        },
        fail: (e)=>{
          this.$f7.preloader.hide();
          this.$f7.dialog.alert("无法获取数据，请重新登录后尝试");
        }
      });
    },
    getFrequently() {
      this.$f7.preloader.show();
      window.qmsdk.callEvent("getFrequently",{
        userId: this.$f7.data.currentUser.userId,
        appCode: this.$f7.id || window.plus.runtime.appid,
        windowsId: window.plus.webview.currentWebview().id,
        success: (r)=>{
          this.$f7.preloader.hide();
          if (r && r.success) {
            this.commonly = r.data;
          } else {
            this.$f7.dialog.alert("无法获取数据，请重新登录后尝试");
          }
        },
        fail: (e)=>{
          this.$f7.preloader.hide();
          this.$f7.dialog.alert("无法获取数据，请重新登录后尝试");
        }
      });
    },
  },
  created() {
    this.getFunctionOptions();
    this.getFrequently();
  }
};
</script>

<style lang="less" scoped>
.lyric-enter,
.lyric-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
.lyric-enter-to,
.lyric-leave {
  opacity: 1;
}
.lyric-enter-active,
.lyric-leave-active {
  transition: all 0.5s;
}
/deep/.page-content {
  background-color: var(--color-fill-background) !important;
  padding-top: calc(88px * var(--ratio));
}
.preservation {
  background-color: #fff;
  padding: 5px 20px 20px;
}
.out {
  background-color: var(--color-fill-background);
  padding: 0;
  margin: 0;
  height: 100%;
  .title-footer {
    text-align: center;
    font-size: 12px;
    color: #8e8e93;
    margin-top: 10px;
  }
  .qm-block {
    background-color: var(--color-fill-grey-inverse);
    border: 1px solid var(--color-fill-grey-inverse);
    // border-radius: calc(16px * var(--ratio));
    margin: calc(20px * var(--ratio)) calc(0px * var(--ratio));
    padding-left: 0px;
    padding-right: 0px;
    .qm-entry {
      display: grid;
      grid-template-columns: repeat(4, 25%);
      grid-row-gap: calc(30px * var(--ratio));
      margin-bottom: 20px;
    }
  }
}
</style>
